package com.caocaog.market.interceptor;

import cn.hutool.core.util.StrUtil;
import com.caocaog.market.annotation.IgnoreAuth;
import com.caocaog.market.entity.Member;
import com.caocaog.market.error.ApiErrorCode;
import com.caocaog.market.service.MemberService;
import com.caocaog.market.session.MemberSession;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.util.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * app应用拦截器
 *
 * @author yuki guo
 * Date 2021/12/14 9:48 上午
 */
@Slf4j
@Component
public class ApiMemberInterceptor extends HandlerInterceptorAdapter {
    @Resource
    private MemberService memberService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof ResourceHttpRequestHandler) return true;

        //获取URL对应的方法上的注解,判断是否需要验证用户的存在与否
        IgnoreAuth annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);

        //如果有@IgnoreAuth注解，则不验证token
        if (annotation != null) {
            return true;
        }

        String token = request.getHeader("X-Access-Token");
        if (StrUtil.isBlank(token)) {
            //没有token 则返回游客账号
//            throw new PeppaException(LoginErrorCode.LACK_TOKEN);
            Member member = memberService.getById("1744628472743387139");
            HttpSession session = getRequest().getSession();
            session.setAttribute(MemberSession.USER, new MemberSession(member.getId()));
            session.setMaxInactiveInterval(30);
        }else {
            //用户手机号
            String userId = JwtUtil.getUsername(token);
            boolean verify = JwtUtil.verify(token, userId, JwtUtil.APP_PASSWORD);
            if (!verify) {
                throw new JeecgBootException(ApiErrorCode.LACK_TOKEN);
            }
            //登录成功把用户信息放入session
            Member member = memberService.getById(userId);
            if (member == null ) {
                throw new JeecgBootException(ApiErrorCode.LACK_TOKEN);
            }

            if(member != null){
                HttpSession session = getRequest().getSession();
                session.setAttribute(MemberSession.USER, new MemberSession(userId));
                session.setMaxInactiveInterval(30);
            }

        }
        return true;
    }


    private HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    public static void main(String[] args) {

        System.out.println(JwtUtil.getUsername("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NDY1NzQxMDh9.7TkWMoVfWw7tw7Hikvw4EHG2Z974xsvMu8PuB3hj1xk"));
    }
}

